package com.fancon.rage.comic;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;

import com.fancon.rage.comic.dao.PhotoJsonDao;
import com.fancon.rage.comic.entity.PhotoJson;
import com.google.appengine.api.datastore.EntityNotFoundException;

@SuppressWarnings("serial")
public class RageCollectPhotoLinkServlet extends HttpServlet {
	protected PhotoJsonDao dao = new PhotoJsonDao();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setHeader("Content-Encoding", "utf-8");
		String action = req.getParameter("action");
		if ("display".equals(action)) {
			long id = Long.parseLong(req.getParameter("id").replace("_", "")); // WTF?
			showRecord(id, req, resp);
		} else if ("thumb".equals(action)) {
			long id = Long.parseLong(req.getParameter("id").replace("_", "")); // WTF?
			showThumb(id, req, resp);
		} else if ("delete".equals(action)) {
			long id = Long.parseLong(req.getParameter("id").replace("_", "")); // WTF?
			delete(id, req, resp);
		} else if ("en".equals(action)) {
			showForm(req, resp, "en");
		} else if ("vn".equals(action)) {
			showForm(req, resp, "vn");
		} else {
			showForm(req, resp, null);
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		handleSubmit(req, resp);
	}

	protected void showForm(HttpServletRequest req, HttpServletResponse resp,
			String countryCode) throws ServletException, IOException {
		List<PhotoJson> enComics = null;
		if (countryCode == null) {
			enComics = dao.getAll(50, 0);
		} else {
			enComics = dao.listByProperty("countryCode", countryCode, 50, 0);
		}
		for (PhotoJson photo : enComics) {
			photo.setTitle(URLDecoder.decode(photo.getTitle(), "UTF-8"));
		}
		req.setAttribute("comics", enComics);
		req.setAttribute("countryCode", countryCode);
		req.setAttribute("root", "ragecollect");
		req.getRequestDispatcher("ragecollect.jsp").forward(req, resp);
	}

	protected void handleSubmit(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		ServletFileUpload upload = new ServletFileUpload();

		try {
			FileItemIterator it = upload.getItemIterator(req);

			PhotoJson photo = new PhotoJson();

			while (it.hasNext()) {
				FileItemStream item = it.next();
				String fieldName = item.getFieldName();
				InputStream fieldValue = item.openStream();

				if ("title".equals(fieldName)) {
					photo.setTitle(URLEncoder.encode(
							Streams.asString(fieldValue, "UTF-8"), "UTF-8"));
					continue;
				}

				if ("thumbFile".equals(fieldName)) {
					photo.setThumbUrl(Streams.asString(fieldValue, "UTF-8"));
					continue;
				}

				if ("imageFile".equals(fieldName)) {
					photo.setImageUrl(Streams.asString(fieldValue, "UTF-8"));
					continue;
				}
				if ("country_code".equals(fieldName)) {
					photo.setCountryCode(Streams.asString(fieldValue, "UTF-8"));
					continue;
				}
			}
			photo.setDate(new Date());
			dao.add(photo);
			resp.sendRedirect("ragecollect");
		} catch (FileUploadException e) {
			throw new ServletException(e);
		}
	}

	protected void delete(long id, HttpServletRequest req,
			HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		// TODO Auto-generated method stub
		PhotoJson photo = null;
		try {
			photo = dao.get(id);
		} catch (EntityNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		dao.delete(photo);
		resp.sendRedirect("ragecollect");
	}

	protected void showRecord(long id, HttpServletRequest req,
			HttpServletResponse resp) throws ServletException, IOException {
		PhotoJson photo = null;
		try {
			photo = dao.get(id);
		} catch (EntityNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		resp.sendRedirect(photo.getImageUrl());
	}

	protected void showThumb(long id, HttpServletRequest req,
			HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		PhotoJson photo = null;
		try {
			photo = dao.get(id);
		} catch (EntityNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		resp.sendRedirect(photo.getThumbUrl());
	}
}
